package com.javabasic.algorithm.sangfor_interview;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2021/12/26 8:41 下午
 *
 * TODO 利用数组实现ArrayList,具有add、set、remove、size等方法
 */
public class CustomArrayList<T> {
    private Object[] elements;
    private int size;
    private int capacity;

    public CustomArrayList(int capacity) {
        this.capacity = capacity;
        /**
         * 不能直接new T[] 数组
         */
        this.elements = new Object[capacity];
        this.size = 0;
    }

    public void add(T element) {
        if (size == capacity) {
            growArray();
        }
        this.elements[size++] = element;
    }

    @SuppressWarnings("unchecked")
    private void growArray() {
        this.capacity = this.capacity + (this.capacity>>1);
        Object[] newElements = new Object[this.capacity];
        System.arraycopy(elements,0,newElements,0,size);
    }

    public void set(int index, T element) {
        if (!checkOfRange(index)) {
            throw new RuntimeException(String.format("index is out of bound for this list"));
        }
        if (!canToFindIndex(index)) {
            throw new RuntimeException(String.format("can not find this index of %s",index));
        }
        this.elements[index] = element;
    }

    public void remove(int index) {
        if (!checkOfRange(index)) {
            throw new RuntimeException(String.format("index is out of bound for this list"));
        }
        if (!canToFindIndex(index)) {
            throw new RuntimeException(String.format("can not find this index of %s",index));
        }
        System.arraycopy(elements,index+1,elements,index,size-index);
    }

    private boolean canToFindIndex(int index) {
        return index < size;
    }

    private boolean checkOfRange(int index) {
        return index >= 0 && index < this.capacity;
    }
}
